package com.yx.service.impl;

import com.yx.mapper.DeptMapper;
import com.yx.mapper.EmpMapper;
import com.yx.pojo.Dept;
import com.yx.pojo.Emp;
import com.yx.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;

    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

//    默认只出现RuntimeException异常才回滚，rollbackFor = Exception.class控制所有异常
    @Transactional(rollbackFor = Exception.class)//spring管理事务
    @Override
    public void delete(Integer id) throws Exception {
        deptMapper.delete(id);//根据id删除部门

//        int i = 1/0;
//        if(true){
//            throw new Exception("出错了");
//        }
        empMapper.deleteByDeptId(id);//根据部门id删除其部门员工
    }


    @Override
    public void add(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insert(dept);
    }

    @Override
    public Dept selectById(Integer id) {
        return deptMapper.selectById(id);
    }

    @Override
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }

}
